export default{
    init(cb){
       const xhr =  window.XMLHttpRequest
       if(xhr.__monitor === true){
         return
       }
       xhr.__monitor = true

       const open = xhr.prototype.open
       xhr.prototype.open = function(method,url){
           this.__xhr = {}
           this.__xhr._method = method
           this.__xhr._url = url
           return open.apply(this,arguments)
       }

       const send = xhr.prototype.send
       xhr.prototype.send = function (){
           this.__xhr._start = Date.now()
           const callback = (type)=> ()=>{
                if(this.response){
                    let size = 0
                    switch(this.responseType){
                        case  'json':
                            size = JSON.stringify(this.response).length
                            break
                        case 'arrayBuffer':
                            size = this.response.byteLength
                            break
                        default:
                            size = this.responseText.length
                    }
                    this.__xhr._event = type
                    this.__xhr._status= this.status 
                    this.__xhr._success = this.status >= 200 && this.status < 300
                    this.__xhr._duration = Date.now() - this.__xhr._start
                    this.__xhr._size = size
                }
                cb(this.__xhr)
           }
           // 请求结束，需要读取信息
           this.addEventListener('load',callback('load'),false)
           this.addEventListener('error',callback('error'),false)
           this.addEventListener('abort',callback('abort'),false)
           return send.apply(this,arguments)
       }
       window.XMLHttpRequest = xhr

       if(window.fetch){
            const fetch = window.fetch
            window.fetch = function(){
                let startTime = Date.now()
                let args = [].slice.call(arguments)
                let firstArg = args[0]
                let method = 'GET'
                let url = null
                if(typeof firstArg === 'string'){
                    url = firstArg
                }else if('Request' in window && firstArg instanceof window.Request){
                    url = firstArg.url
                    method = firstArg.method? firstArg.method: method
                }else {
                    url = '' + firstArg
                }
                let fetchInfo = {
                    method,url,status:null
                }
                return fetch.apply(this,args).then(res=>{
                    fetchInfo.status = res.status
                    fetchInfo.type = 'fetch'
                    fetchInfo.duration = Date.now() - startTime
                    cb(fetchInfo)
                    return res
                })
            }
       }
      
    }
}